package com.filemanager;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by IntelliJ IDEA.
 * User: Anna.Bulenkova
 * Date: 26.10.11
 * Time: 17:40
 */
public class FileServer extends Thread {
    private Socket mySocket;
    private int myConnectionsNumber;   //will be used later to handle maximum connections number to the server

    public FileServer(int connectionsNumber, Socket socket) {
        //just setting default parameters here
        this.myConnectionsNumber = connectionsNumber;
        this.mySocket = socket;
        setDaemon(true);
//        setPriority(NORM_PRIORITY);
    }

    public void run() {
        try {
            InputStream inputStream = mySocket.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);
            String inputLine;
            XMLReader myReader = XMLReaderFactory.createXMLReader();
            myReader.parse(new InputSource(inputStream));
            System.out.println(myReader);






//            MyJAXBObject unmarshalledObject = Utils.getObjectFromXML(source);
//            System.out.println("Get object" + unmarshalledObject);
//            while ((inputLine = source.readLine()) != null) {
//                System.out.println(inputLine);
//                out.println("got some shit from you, dude!");
//            }
//            Lts send smth to client now

//            TODO: create received data handling and reply
            in.close();
            out.close();
            mySocket.close(); //after data handling

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public static void main(String[] args) throws IOException {

        try
        {
            int i = 0; //initial number of connections
            ServerSocket listener = new ServerSocket(3333, 0, InetAddress.getByName("localhost"));
            System.out.println("File server is listening on port " + 3333);

//TODO: attach smth like writeToLog here

            // binding to port
            while(true)
            {
                // wait for a new connection, starting a thread
                (new FileServer(i, listener.accept())).start();
                i++;
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }

    }
}
